package com.store;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.model.Product;
import com.utils.HibernateUtil;

public class StoreH2Hib implements DataStore {

	Session session = null;
	SessionFactory sessionFactory = null;
	
	@Override
	public void InsertProduct(Product pr) {	
		session.beginTransaction();
		session.save(pr);
		session.getTransaction().commit();
	}

	@Override
	public void close() {		
		session.close();
	}

	@Override
	public void open(String db) {		
		sessionFactory = HibernateUtil.getSessionFactory();
		session =sessionFactory.openSession();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Product findByDescription(String descriere) {
		
		Query query = session.createQuery("from Product where descriere = :descr");
		query.setParameter("descr", descriere);
		List<Product> res = query.list();
		if(res.size() == 0)
		{
			//aici se poate sa existe produsul dar sa nu fie filtratata bine descrierea. Need atention
			return null;
		}else {
			return (Product) res.get(0);
		}
	}

	@Override
	public void addPretProduct(Product pr) {
		session.beginTransaction();
		session.saveOrUpdate(pr);
		session.getTransaction().commit();
	}
}
